package com.yinsw.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yinsw.dao.HouseDao;
import com.yinsw.entity.HouseEntity;
import com.yinsw.entity.TbRegion;
import com.yinsw.entity.TbUser;
import com.yinsw.service.HouseService;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author printguy
 * @version 1.0.0
 * @className HouseServiceImpl.java
 * @description TODO
 * @createTime 2022年07月18日 18:57:00
 */
@Service
public class HouseServiceImpl implements HouseService {

    private final HouseDao houseDao;
    private final RestHighLevelClient client;
    private final RedisTemplate<String,String> redisTemplate;
    public HouseServiceImpl(HouseDao houseDao, RestHighLevelClient client, RedisTemplate<String, String> redisTemplate) {
        this.houseDao = houseDao;
        this.client = client;
        this.redisTemplate = redisTemplate;
    }
    @Override
    public List<HouseEntity> list(Map<String,Object> map) {
        String category = (String) map.get("category");
        String type = (String) map.get("type");
        String title = (String) map.get("title");
        List<HouseEntity> list = new ArrayList<>();
        SearchRequest searchRequest = new SearchRequest("house");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //分页
        String page = (String) map.get("page");
        String limit = (String) map.get("limit");
        if (page==null){
            page = "1";
        }
        if (limit==null){
            limit = "2";
        }
        searchSourceBuilder.from((Integer.valueOf(page)-1)*Integer.valueOf(limit));
        searchSourceBuilder.size(Integer.valueOf(limit));

        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        if (StringUtils.isNotEmpty(category)){
            boolQueryBuilder.must(QueryBuilders.termQuery("category",category));
        }
        if (StringUtils.isNotEmpty(type)) {
            boolQueryBuilder.must(QueryBuilders.termQuery("type",type));
        }
        if (StringUtils.isNotEmpty(title)) {
            boolQueryBuilder.must(QueryBuilders.matchQuery("unit",title));
        }
        searchSourceBuilder.query(boolQueryBuilder);
        searchRequest.source(searchSourceBuilder);
        try {
            SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
            SearchHits hits = searchResponse.getHits();
            for (SearchHit hit : hits.getHits()) {
                String sourceAsString = hit.getSourceAsString();
                HouseEntity houseEntity = JSONObject.parseObject(sourceAsString, HouseEntity.class);
                list.add(houseEntity);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return list;
    }

    @Override
    public List<TbRegion> provinceList() {
        return houseDao.provinceList();
    }

    @Override
    public List<TbRegion> cityList(Integer id) {
        return houseDao.cityList(id);
    }

    @Override
    public List<TbRegion> countyList(Integer id) {
        return houseDao.countyList(id);
    }

    @Override
    public int save(HouseEntity houseEntity) {
        //拼接配套设施
        String[] equipments = houseEntity.getEquipments();
        if (equipments!=null){
            String str = "";
            for (String equipment : equipments) {
                str += ","+equipment;
            }
            str = str.substring(1);
            houseEntity.setEquipment(str);
        }


        //拼接房屋标签
        String str2 = "";
        String[] tags = houseEntity.getTags();
        if (tags!=null){
            for (String tag : tags) {
                str2 += ","+tag;
            }
            str2 = str2.substring(1);
            houseEntity.setTag(str2);
        }

        //拼接推荐行业
        String str3 = "";
        String[] industrys = houseEntity.getIndustrys();
        if (industrys!=null){
            for (String industry : industrys) {
                str3 += ","+industry;
            }
            str3 = str3.substring(1);
            houseEntity.setIndustry(str3);
        }

        //拼接商铺特征
        String str4 = "";
        String[] features = houseEntity.getFeatures();
        if (features!=null){
            for (String feature : features) {
                str4 += ","+feature;
            }
            str4 = str4.substring(1);
            houseEntity.setFeature(str4);
        }

        //拼接客流人群
        String str5 = "";
        String[] consumers = houseEntity.getConsumers();
        if (consumers!=null){
            for (String consumer : consumers) {
                str5 += ","+consumer;
            }
            str5 = str5.substring(1);
            houseEntity.setConsumer(str5);
        }

        //创建时间
        houseEntity.setCreateDate(new Date());
        //创建人id
        String s = redisTemplate.opsForValue().get("user");
        String parse = (String) JSON.parse(s);
        TbUser user = JSONObject.parseObject(parse, TbUser.class);
        houseEntity.setCreator(user.getId());

        int save = houseDao.save(houseEntity);
        List<HouseEntity> houseEntityList = houseDao.selectList(null);
        BulkRequest bulkRequest = new BulkRequest("house");
        houseEntityList.forEach(h->{
            IndexRequest indexRequest = new IndexRequest();
            indexRequest.id(h.getId().toString());
            String equipment = h.getEquipment();
            if (equipment!=null){
                h.setEquipments(equipment.split(","));
            }
            String tag = h.getTag();
            if (tag!=null){
                h.setTags(tag.split(","));
            }
            String industry = h.getIndustry();
            if (industry!=null){
                h.setIndustrys(industry.split(","));
            }
            String feature = h.getFeature();
            if (feature!=null){
                h.setFeatures(feature.split(","));
            }
            String consumer = h.getConsumer();
            if (consumer!=null){
                h.setConsumers(consumer.split(","));
            }
            String houseImg = h.getHouseImg();
            if (houseImg!=null){
                h.setHouseImgs(houseImg.split(","));
            }
            indexRequest.source(JSONObject.toJSONString(h), XContentType.JSON);
            bulkRequest.add(indexRequest);
        });
        try {
            client.bulk(bulkRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return save;
    }

    @Override
    public TbUser getUser(String name) {
        return houseDao.getUser(name);
    }

}
